package com.czk.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czk.common.constant.ProductConstant;
import com.czk.common.utils.PageUtils;
import com.czk.common.utils.Query;
import com.czk.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.czk.gulimall.product.dao.AttrDao;
import com.czk.gulimall.product.dao.AttrGroupDao;
import com.czk.gulimall.product.dao.CategoryDao;
import com.czk.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.czk.gulimall.product.entity.AttrEntity;
import com.czk.gulimall.product.entity.AttrGroupEntity;
import com.czk.gulimall.product.entity.CategoryEntity;
import com.czk.gulimall.product.service.AttrService;
import com.czk.gulimall.product.service.CategoryService;
import com.czk.gulimall.product.vo.AttrGroupRelationVo;
import com.czk.gulimall.product.vo.AttrResponseVo;
import com.czk.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attrVo) {
        // 保存基本信息
        AttrEntity attrEntity = new AttrEntity();
        // 拷贝信息
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.save(attrEntity);
        // 保存关联关系,基本属性才保留
        if (attrVo.getAttrType() == 1) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            // 分组id
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            // 属性id
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }

    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE_ENUM.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        // 有上级id的时候
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((wra) -> {
                wra.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        // 拿到记录
        List<AttrEntity> records = page.getRecords();
        // 设置分组名称和分类名称
        List<AttrResponseVo> respVos = records.stream().map(attrEntity -> {
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            // 拷贝属性
            BeanUtils.copyProperties(attrEntity, attrResponseVo);
            // 基本属性才设置值
            if ("base".equalsIgnoreCase(attrType)) {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attrAttrgroupRelationEntity != null) {
                    // 拿到分组id
                    Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
                    // 拿到分组名称
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    if (attrGroupEntity != null) {
                        // 设置分类和分组的名字
                        attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }

                }
            }
            // 设置分类信息
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrResponseVo.setCatelogName(categoryEntity.getName());
            }
            return attrResponseVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }
    @Cacheable(value = "attr",key = "'attrInfo:'+#root.args[0]") // 加入缓存
    @Override
    public AttrResponseVo getAttrInfo(Long attrId) {
        // 得到详细信息
        AttrEntity attrEntity = this.getById(attrId);
        // 拿到分组信息
        AttrResponseVo attrResponseVo = new AttrResponseVo();
        // 拷贝信息
        BeanUtils.copyProperties(attrEntity, attrResponseVo);

        // 查出分组信息
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (attrAttrgroupRelationEntity != null) {
            // 设置分组id
            attrResponseVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
            // 查询分组名称
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrId());
            if (attrGroupEntity != null) {
                // 设置名称
                attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }

        // 设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        //
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrResponseVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            attrResponseVo.setCatelogName(categoryEntity.getName());
        }
        return attrResponseVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        // 对基本数据进行修改
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        // 基本信息的修改
        this.updateById(attrEntity);
        // 修改分组关联
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
        attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());


        Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
        if (count > 0) {
            attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
        } else {
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    /**
     * 根据分组id查找关联的所有属性
     *
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        if (attrIds == null || attrIds.size() == 0) {
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);

        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        // 删除关联关系
        //  attrAttrgroupRelationDao.delete(new QueryWrapper<>().eq("attr_id","").eq("attr_group_id",1L))
        // 转为对象
        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            // f返回
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(collect);
    }

    /**
     * 获取当前分组没有关联的所有属性
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        // 当前分组只能关联自己所属分类的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        // 拿到分类id
        Long catelogId = attrGroupEntity.getCatelogId();
        // 当前分组只能关联别的分组没有引用的属性
        // 当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        // 拿到其他的属性集合
        List<Long> collect = group.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        // 拿到其关联的所有属性
        List<AttrAttrgroupRelationEntity> groups = null;
        if (collect != null && collect.size() > 0) {
            groups = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        }
        List<Long> attrsId = null;
        if (groups != null && collect.size() > 0) {
            attrsId = groups.stream().map((item) -> {
                return item.getAttrId();
            }).collect(Collectors.toList());
        }
        // 从当前分类移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE_ENUM.getCode());
        if (attrsId != null && attrsId.size() > 0) {
            wrapper.notIn("attr_id", attrsId);
        }
        // 拿到模糊查询条件
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> iPage = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(iPage);
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if (attrIds != null && attrIds.size()>0) {
            wrapper.in("attr_id", attrIds);
            wrapper.eq("search_type", 1);
            List<AttrEntity> entities = this.baseMapper.selectList(wrapper);
            List<Long> collect = entities.stream().map(entity -> {
                return entity.getAttrId();
            }).collect(Collectors.toList());
            return collect;
        }
        return Arrays.asList();
    }
}